﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using YiMeiJiaLibModel.Assembly;
using YiMeiJiaLibModel.Business;
using YiMeiJiaLibModel.Config;
using YiMeiJiaService.Assembly.DB;
namespace YiMeiJiaService.Assembly
{
    public static class _HttpClient
    {
        /// <summary>
        /// 专用请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static async Task<ApiResponse<T, T2>> Action<T, T2>(string action, object json, bool? authorize = false, bool? selfHost = false)
        {
            var url = ApiConf.Api(action, selfHost);
            if (url == null)
            {
                return new ApiResponse<T, T2>() { code = 0, msg = "找不到合法的请求路径" };
            }
            var method = url.Split(',')[1];
            if (method.ToLower() == "post")
            {
                return await ActionPost<T, T2>(url.Split(',')[0], json, authorize);
            }
            else
            {
                var data = await Get(url.Split(',')[0]);
                return JsonSerializer.Deserialize<ApiResponse<T, T2>>(data);
            }
        }
        public static async Task<ApiResponse<T>> Action<T>(string action, object json, bool? authorize = false, bool? selfHost = false)
        {
            var url = ApiConf.Api(action, selfHost);
            if (url == null)
            {
                return new ApiResponse<T>() { code = 0, msg = "找不到合法的请求路径" };
            }
            var method = url.Split(',')[1];
            if (method.ToLower() == "post")
            {
                return await ActionPost<T>(url.Split(',')[0], json, authorize);
            }
            else
            {
                var data = await Get(url.Split(',')[0]);
                return JsonSerializer.Deserialize<ApiResponse<T>>(data);
            }
        }
        private static async Task<ApiResponse<T, T2>> ActionPost<T, T2>(string url, object json, bool? authorize = false)
        {

            using var httpClient = new HttpClient();
            // 如果需要传递授权
            if (Convert.ToBoolean(authorize))
                await AddAuthorizeHeader(httpClient);

            var jsonRequest = JsonSerializer.Serialize(json);
            var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync(url, content);
            if (response.IsSuccessStatusCode)
            {
                response.EnsureSuccessStatusCode();
            }
            else
            {

            }

            var str = await response.Content.ReadAsStringAsync();
            if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                var i = LitJson.JsonMapper.ToObject<ApiResponse<int>>(str);
                return new ApiResponse<T,T2>()
                {
                    code = i.code,
                    status = i.status,
                    msg = i.msg,
                };

            }
            //var js = JsonSerializer.Deserialize<ApiResponse<T,T2>>(str);
            var js = LitJson.JsonMapper.ToObject<ApiResponse<T, T2>>(str);
            return js;

        }




        private static async Task<ApiResponse<T>> ActionPost<T>(string url, object json, bool? authorize = false)
        {

            using var httpClient = new HttpClient();
            // 如果需要传递授权
            if (Convert.ToBoolean(authorize))
                await AddAuthorizeHeader(httpClient);
            var jsonRequest = JsonSerializer.Serialize(json);
            var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync(url, content);
            if(response.IsSuccessStatusCode )
            {
                response.EnsureSuccessStatusCode();
            }
            else
            {
              
            }
             
            var str = await response.Content.ReadAsStringAsync();
            if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                var i = LitJson.JsonMapper.ToObject<ApiResponse<int>>(str);
                return new ApiResponse<T>()
                {
                    code = i.code,
                    status = i.status,
                    msg = i.msg,
                };
            }
            if(response.StatusCode == System.Net.HttpStatusCode.BadGateway)
            {
                return new ApiResponse<T>()
                {
                    code = 502,
                    status = false,
                    msg = "502 api宕机。",
                };
            }
            var js = LitJson.JsonMapper.ToObject<ApiResponse<T>>(str);
            //var js = JsonSerializer.Deserialize<ApiResponse<T>>(str);
            return js;

        }


        /// <summary>
        /// 添加授权头
        /// </summary>
        /// <param name="httpClient"></param>
        /// <returns></returns>
        public static async Task AddAuthorizeHeader(HttpClient httpClient)
        {
            var db = await YMJLifeSqlite.Db();
            var authorize = await db.Table<AdnroidTokens>().FirstOrDefaultAsync();
            if (authorize != null)
            {
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {authorize.Token}");
                //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(" ", authorize.Token);
            }
        }


        /// <summary>
        /// 简单get
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<string> Get(string url)
        {
            using var httpClient = new HttpClient();
            var response = await httpClient.GetAsync(url);
            var content = await response.Content.ReadAsStringAsync();
            return content;
        }

        public static async Task<string> Post(string url, object json)
        {
            using var httpClient = new HttpClient();
            var jsonRequest = JsonSerializer.Serialize(json);
            var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync(url, content);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();

        }
    }
}
